package com.cloudfast.common.jdbc.subtable.impl;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;

import com.cloudfast.common.jdbc.subtable.SubTableRule;

/**
 * 月份规则
 *
 * @author liuyw
 */
public class MonthSubTableRule implements SubTableRule {

    @Override
    public <T> String getName(T entity, String field) {
        SimpleDateFormat f = new SimpleDateFormat("yyyyMM");
        // filed为空时的处理
        if (StringUtils.isEmpty(field)) {
            return f.format(new Date());
        }
        String tableName = "";
        try {
            // field不为空的处理
            Field[] fields = entity.getClass().getDeclaredFields();
            for (Field _field : fields) {
                if (_field.getName().equals(field)) {
                    _field.setAccessible(true);
                    Object value = _field.get(entity);
                    tableName = f.format(f.format(value));
                    break;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return tableName;
    }

}
